package com.ustcinfo.study.hive.r5.liuqiang;

import java.sql.*;

public class LiuHiveDemo {
    // hive 驱动
    private static String DRIVER = "org.apache.hive.jdbc.HiveDriver";
    // hive链接地址
    private static String URL = "jdbc:hive2://192.168.110.102:10000/default";
    //hive用户名
    private static String USERNAME = "root";
    // hive密码
    private static String PASSWORF = "";


    private static Connection connection = null;
    private static Statement statement = null;
    private static ResultSet resultSet = null;

    // 查询tables sql
    private static String showTableSql = "show tables";


    // 倒序显示同一域名的ip数
    private static String doCountSql = "select domain_name,count(*) num from dns_liuqiang group by domain_name  order by num desc ";


    public static void main(String[] args) throws SQLException {

        //  加载hive驱动
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            System.out.println("驱动加载失败");
            e.printStackTrace();
        }

        try {
            // 连接root
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORF);
            if (connection != null) {
                System.out.println("hive 连接成功");
            } else {
                System.out.println("hive 连接失败");
            }

            statement = connection.createStatement();

            // 获取数据库中所有的表
            resultSet = statement.executeQuery(showTableSql);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1));
            }
            //获取结果集
            resultSet = statement.executeQuery(doCountSql);
            while (resultSet.next()) {
                System.out.println(resultSet.getString(1) + "\t\t" + resultSet.getInt(2));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {//关闭资源
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}
